package com.sp.scmdb.spring;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import org.apache.commons.collections.CollectionUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import com.sp.scmdb.bean.EmpReportBean;
import com.sp.scmdb.common.CommonParamter;
import com.sp.scmdb.entity.Report_Upload;
import com.sp.scmdb.service.EmpReportService;
import com.sp.scmdb.webservice.model.EmpCountModel;
import com.sp.scmdb.webservice.model.EmpDayReportModel;
import com.sp.scmdb.webservice.model.ReturnResponse;
import com.sp.scmdb.webservice.service.UploadDataService;
import com.sp.scmdb.webservice.service.UploadLabelIOService;
import com.sp.scmdb.webservice.suport.CastorSerializer;
import com.sp.scmdb.webservice.suport.InitUploadIndentity;

public class SpringInit implements InitializingBean, DisposableBean {

	private ScheduledExecutorService scanCredentialTaskExecutorService;
	private UploadLabelIOService uploadLabelIOService;
	private ExecutorService executorService;
	private EmpReportService empReport;

	public void setEmpReportService(EmpReportService empReport) {
		this.empReport = empReport;
	}

	public void setUploadLabelIOService(
			UploadLabelIOService uploadLabelIOService) {
		this.uploadLabelIOService = uploadLabelIOService;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if (InitUploadIndentity.initIndentity()) {
			executorService = Executors.newFixedThreadPool(5);
			executorService.execute(new UploadTask());
			uploadLabelIOService.startThread();
		}
	}

	@Override
	public void destroy() throws Exception {
		shutdownIfNotNull(scanCredentialTaskExecutorService);
	}

	public void init() {

	}

	private static void shutdownIfNotNull(ExecutorService executorService) {
		if (executorService != null) {
			executorService.shutdown();
		}
	}

	private class UploadTask implements Runnable {
		@SuppressWarnings("unchecked")
		public void run() {
			int refresh = 5;
			String result = CommonParamter.CHECK_FAIL;
			while (true) {
				EmpDayReportModel model = new EmpDayReportModel();
				EmpCountModel model1 = new EmpCountModel();
				try {
					Thread.sleep(refresh * 1000);
					List<Report_Upload> ruList = empReport.findUpload();
					if (CollectionUtils.isNotEmpty(ruList)) {
						Report_Upload ru = ruList.get(0);
						if (ru.getIsUsed().equals("1")) {
							try {
								refresh = Integer.parseInt(ru.getRefreshTime());
								List<EmpReportBean> list = empReport
										.uploadReport();
								model.setUserId(CommonParamter.userID);
								model.setPassword(CommonParamter.password);
								model.setListBean(list);
								CastorSerializer serializerTool = new CastorSerializer();
								ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
								serializerTool
										.addMappingLocation("com/sp/scmdb/webservice/mapping/mapping.xml");
								UploadDataService upload = (UploadDataService) ApplicationContext
										.getBean("uploadService");

								serializerTool.marshal(model, byteOutputStream,
										"UTF-8");
								String str = new String(byteOutputStream
										.toByteArray());
								result = upload.uploadDayReport(str);

								Map<String, List> map = empReport
										.numberPeople();
								model1.setUserId(CommonParamter.userID);
								model1.setPassword(CommonParamter.password);
								for (Map.Entry<String, List> ee : map
										.entrySet()) {
									model1.setEntryCount(ee.getKey());
									model1.setListBean(ee.getValue());
								}
								byteOutputStream = new ByteArrayOutputStream();
								serializerTool.marshal(model1,
										byteOutputStream, "UTF-8");
								str = new String(byteOutputStream.toByteArray());
								result = upload.uploadEmpCount(str);
								ReturnResponse response = (ReturnResponse) serializerTool
										.unmarshal(new ByteArrayInputStream(
												result.getBytes()), "GB2312");
								result = response.getDescription();
								ru.setLastTime(new DateTime()
										.toString("yyyy-MM-dd HH:mm:ss"));
								ru.setState(result);
								empReport.initORcancel(ru);
							} catch (javax.xml.ws.WebServiceException e) {
								e.printStackTrace();
								if ("Could not send Message.".equals(e
										.getMessage())) {
									ru.setState("无法连接到服务器！");
									empReport.initORcancel(ru);
									continue;
								}
							} catch (Exception e) {
								e.printStackTrace();
								ru.setState("数据不匹配！");
								empReport.initORcancel(ru);
								continue;
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
			}
		}
	}
}
